import {
  Injectable,
  ConflictException,
  ForbiddenException,
  Param,
  NotFoundException,
} from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { PrismaService } from '../prisma/prisma.service';
import { ApiResponse } from 'src/common/reponse.interface'; // 引入统一响应格式
@Injectable()
export class RoleService {
  constructor(private prisma: PrismaService) {}
  // 创建角色
  async create(createRoleDto: CreateRoleDto): Promise<ApiResponse<any>> {
    const { name } = createRoleDto;
    // 检查用户名是否已经存在
    const existingRole = await this.prisma.role.findFirst({
      where: { name },
    });

    if (existingRole) {
      throw new ConflictException('用户名已存在');
    }
    const result = await this.prisma.role.create({
      data: { name },
    });
    return {
      statusCode: 200,
      message: '创建成功',
      data: result,
    };
  }

  // 查询所有角色
  async findAll(): Promise<ApiResponse<any>> {
    const role = await this.prisma.role.findMany({
      include: {
        menus: true,
      },
    });

    const result = role.map((role) => ({
      id: role.id,
      name: role.name,
    }));

    return {
      statusCode: 200,
      message: '角色信息查询成功',
      data: result,
    };
  }
  // 更新用户角色
  async update(userId: number, newRoleId: number): Promise<ApiResponse<any>> {
    // 获取当前登录用户角色信息
    const role = await this.findOne(userId);
    const currentUserRole = role.data.name;

    // 判断是否是管理员角色
    if (currentUserRole !== 'ADMIN') {
      throw new ForbiddenException('只有管理员才能修改角色');
    }

    // 更新用户的角色
    const updatedUser = await this.prisma.user.update({
      where: { id: userId },
      data: { roleId: newRoleId },
    });

    return {
      statusCode: 200,
      message: '修改成功',
      data: updatedUser,
    };
  }

  // 删除角色
  async remove(@Param('id') id: number): Promise<ApiResponse<any>> {
    const role = await this.findOne(id);
    if (!role) {
      throw new NotFoundException('没有查询到角色');
    }
    const result = await this.prisma.role.delete({
      where: { id },
    });
    return {
      statusCode: 200,
      message: '删除成功',
      data: result,
    };
  }

  // 查询角色信息
  async findOne(id: number): Promise<ApiResponse<any>> {
    const result = await this.prisma.role.findUnique({
      where: {
        id: id,
      },
      include: {
        menus: {
          include: {
            menu: true,
          },
        },
      },
    });
    if (!result) {
      throw new NotFoundException('没有查询到角色');
    }
    return {
      statusCode: 200,
      message: '获取成功',
      data: result,
    };
  }

  // 统计各个角色用户数量
  async countRoleUser(): Promise<ApiResponse<any>> {
    // 首先进行 groupBy 查询
    const groupedUsers = await this.prisma.user.groupBy({
      by: ['roleId'],
      _count: {
        _all: true,
      },
    });

    // 获取所有涉及的 roleId
    const roleIds = groupedUsers.map((user) => user.roleId);

    // 查询所有相关的角色信息
    const roles = await this.prisma.role.findMany({
      where: {
        id: { in: roleIds },
      },
      select: {
        id: true,
        name: true,
      },
    });

    // 合并结果
    const result = groupedUsers.map((user) => {
      const role = roles.find((r) => r.id === user.roleId);
      return {
        roleId: user.roleId,
        roleName: role ? role.name : '未定义角色',
        count: user._count._all,
      };
    });

    return {
      statusCode: 200,
      message: '获取成功',
      data: result,
    };
  }
}
